package com.amado.course42Socket.tcp.homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by Administrator on 2018/8/7.
 */
public class FileCopyService {
	private int port = 8888;
	private ServerSocket serverSocket;

	public FileCopyService() throws Exception {
		serverSocket = new ServerSocket(port);
		System.out.println("服务器启动!");
	}

	public void service() {
		while (true) {
			OutputStream outputStream = null;
			try {
				Socket socket = serverSocket.accept();
				System.out.println(socket.getInetAddress() + "  " + socket.getPort());
				PrintWriter printwriter = new PrintWriter(socket.getOutputStream(), true);
				printwriter.print("你已经连接到服务器");
				// 开启一个线程去读取对方的聊天的信息
				InputStream inputStream = socket.getInputStream();
				File file = new File("D:\\temp\\b.jpg");
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				if (!file.exists()) {
					file.createNewFile();
				}
				outputStream = new FileOutputStream(file);
				byte[] content = new byte[1024];
				int len = 0;
				while ((len = inputStream.read(content)) != -1) {
					outputStream.write(content, 0, len);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					outputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("接收成功");

		}

	}

	public static void main(String[] args) throws Exception {
		FileCopyService server = new FileCopyService();
		server.service();
	}
}
